﻿using System.Linq;
using System.Web.UI.HtmlControls;

namespace Cms.Web.Framework.Extensions
{
    public static class HtmlControlExtensions
    {
        public static bool HasClass(this HtmlControl control, string className)
        {
            return !string.IsNullOrEmpty(control.Attributes["class"]) &&
                   control.Attributes["class"].Trim().Split(" ".ToCharArray()).Any(c => c == className);
        }

        public static void AddClass(this HtmlControl control, string className)
        {
            if (!string.IsNullOrEmpty(control.Attributes["class"]))
            {
                // Check if the class already exists
                if (control.Attributes["class"].Trim().Split(" ".ToCharArray()).Any(c => c == className))
                    return;
                className = control.Attributes["class"] + " " + className;
            }
            control.Attributes.Add("class", className);
        }

        public static void RemoveClass(this HtmlControl control, string className)
        {
            string currentClass = control.Attributes["class"];
            if (string.IsNullOrEmpty(currentClass))
                return;

            // Check if class contains more than one class
            if (currentClass.Trim().IndexOf(" ") > 0 && currentClass.Trim().Length > 0)
            {
                string newClasses = string.Join(" ", currentClass.Split(" ".ToCharArray()).Where(s => s != className));
                control.Attributes.Add("class", newClasses);
            }
            else 
            {
                // currentClass contains only one class
                if (currentClass == className)
                    control.Attributes.Remove("class");
            }
        }
    }
}